﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;

[ExecuteInEditMode]
public class TestSmoothCurveMove : MonoBehaviour
{

    /// <summary>The path to follow</summary>
    [Tooltip("The path to follow")]
    public SmoothPathCurve m_Path;
    public enum UpdateMethod
    {
        /// <summary>Updated in normal MonoBehaviour Update.</summary>
        Update,
        /// <summary>Updated in sync with the Physics module, in FixedUpdate</summary>
        FixedUpdate,
        /// <summary>Updated in normal MonoBehaviour LateUpdate</summary>
        LateUpdate
    };
    [Tooltip("When to move the cart, if Velocity is non-zero")]
    public UpdateMethod m_UpdateMethod = UpdateMethod.Update;

    public SmoothPathCurve.PositionUnits m_PositionUnits = SmoothPathCurve.PositionUnits.Distance;

    [Tooltip("Move the cart with this speed along the path.  The value is interpreted according to the Position Units setting.")]
    [FormerlySerializedAs("m_Velocity")]
    public float m_Speed;

    [Tooltip("The position along the path at which the cart will be placed.  This can be animated directly or, if the velocity is non-zero, will be updated automatically.  The value is interpreted according to the Position Units setting.")]
    [FormerlySerializedAs("m_CurrentDistance")]
    public float m_Position;

    void FixedUpdate()
    {
        if (m_UpdateMethod == UpdateMethod.FixedUpdate)
            SetCartPosition(m_Position + m_Speed * Time.deltaTime);
    }

    void Update()
    {
        float speed = Application.isPlaying ? m_Speed : 0;
        if (m_UpdateMethod == UpdateMethod.Update)
            SetCartPosition(m_Position + speed * Time.deltaTime);
    }

    void LateUpdate()
    {
        if (!Application.isPlaying)
            SetCartPosition(m_Position);
        else if (m_UpdateMethod == UpdateMethod.LateUpdate)
            SetCartPosition(m_Position + m_Speed * Time.deltaTime);
    }

    void SetCartPosition(float distanceAlongPath)
    {
        if (m_Path != null)
        {
            m_Position = m_Path.StandardizeUnit(distanceAlongPath, m_PositionUnits);
            transform.position = m_Path.EvaluatePositionAtUnit(m_Position, m_PositionUnits);
            transform.rotation = m_Path.EvaluateOrientationAtUnit(m_Position, m_PositionUnits);
        }
    }

}
